package com.sls.game.supply.deal;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import com.google.gson.Gson;
import com.sls.core.common.CommonUtil;
import com.sls.core.http.HttpClient;
import com.sls.core.socket.Head;
import com.sls.core.util.PropertiesUtil;
import com.sls.core.util.UtilMD5Encryption;
import com.sls.game.common.DeductionRefund;
import com.sls.game.dao.DownstreamUserDAO;
import com.sls.game.dao.GoodsOrderDAO;
import com.sls.game.dao.GoodsSupplyManageDAO;
import com.sls.game.dao.SevenNineNineSixDAO;
import com.sls.game.parser.snns.ParseResponseInfo;
import com.sls.game.pojo.DeductionRefundInfo;
import com.sls.game.pojo.GoodsOrderInfo;
import com.sls.game.pojo.SLSHttpInterfaceInfo;
import com.sls.game.pojo.snns.SevenNineNineSixProduct;
import com.sls.game.pojo.snns.SevenNineNineSixRespInfo;

public class SevenNineNineSixTradeDeal {

	public static Logger log = Logger
			.getLogger(SevenNineNineSixTradeDeal.class);
	private static String filename = "snns.properties";

	/**
	 * 交易处理
	 * 
	 * @param info
	 * @param originalGoodsId
	 * @param orderId
	 * @param orderTime
	 * @param paymentOrderNo
	 * @param head
	 * @param goodsOrderDAO
	 * @param goodsSupplyManageDAO
	 * @param snnsDAO
	 * @param downstreamUserDAO
	 * @return
	 */
	public static String dealTradeResultOfSnns(SLSHttpInterfaceInfo info,
			String originalGoodsId, String orderId, String orderTime,
			String paymentOrderNo, Head head, GoodsOrderDAO goodsOrderDAO,
			GoodsSupplyManageDAO goodsSupplyManageDAO,
			SevenNineNineSixDAO snnsDAO, DownstreamUserDAO downstreamUserDAO) {
		SevenNineNineSixRespInfo resInfo = trade(info, originalGoodsId,
				orderId, orderTime, head, goodsOrderDAO, goodsSupplyManageDAO,
				snnsDAO);
		// 返回给上层对象
		SLSHttpInterfaceInfo sLSHttpInterfaceInfo = new SLSHttpInterfaceInfo();
		if (resInfo != null) {
			String result = resInfo.getResult();
			if ("true".equals(result)) { // 处理中
				sLSHttpInterfaceInfo.setResMsg("SUCCESS");
				sLSHttpInterfaceInfo.setFailedCode("209");
				sLSHttpInterfaceInfo.setFailedReason("处理中");
				sLSHttpInterfaceInfo.setPtOrderNo(info.getPtOrderNo());
				sLSHttpInterfaceInfo.setStatus("ORDER_UNDERWAY");
				sLSHttpInterfaceInfo.setSupOrderNo(orderId);
			} else if ("false".equals(result)) { // 失败
				sLSHttpInterfaceInfo.setResMsg("FAILED");
				sLSHttpInterfaceInfo.setFailedCode("208");
				sLSHttpInterfaceInfo.setFailedReason("充值失败");
				sLSHttpInterfaceInfo.setPtOrderNo(info.getPtOrderNo());
				sLSHttpInterfaceInfo.setStatus("ORDER_FAILED");
				sLSHttpInterfaceInfo.setSupOrderNo(orderId);

				GoodsOrderInfo goodsOrderInfo = new GoodsOrderInfo();
				DeductionRefundInfo dedInfo = null;
				String paymentStatus = "";
				// 退款
				dedInfo = DeductionRefund.invokeDeductRefund(info, orderId,
						"1", orderTime, paymentOrderNo, head, goodsOrderDAO);
				if (dedInfo != null) {
					paymentStatus = dedInfo.getPaymentStatus();
				}
				if ("1".equals(paymentStatus)) { // 成功
					goodsOrderInfo.setIsPay("3"); // 退款成功
					// 退款成功，通知下游用户
					DeductionRefund.noticeUserRefundMsg(orderId, dedInfo,
							goodsOrderDAO, downstreamUserDAO, null);

				} else if ("2".equals(paymentStatus)) {
					goodsOrderInfo.setIsPay("2"); // 退款失败
				}
				try {
					// 更新订单
					updateGoodsOrder(orderId, head, goodsOrderInfo,
							goodsOrderDAO);
				} catch (Exception e) {
					log.error("请求ID：" + head.getRequestId() + "根据退款状态更新订单异常！",
							e);
				}
			} else {
				sLSHttpInterfaceInfo.setResMsg("SUCCESS");
				sLSHttpInterfaceInfo.setFailedCode("210");
				sLSHttpInterfaceInfo.setFailedReason("订单存疑");
				sLSHttpInterfaceInfo.setPtOrderNo(info.getPtOrderNo());
				sLSHttpInterfaceInfo.setStatus("ORDER_DUBIOUS");
				sLSHttpInterfaceInfo.setSupOrderNo(orderId);
			}
		} else {
			sLSHttpInterfaceInfo.setResMsg("SUCCESS");
			sLSHttpInterfaceInfo.setFailedCode("210");
			sLSHttpInterfaceInfo.setFailedReason("订单存疑");
			sLSHttpInterfaceInfo.setPtOrderNo(info.getPtOrderNo());
			sLSHttpInterfaceInfo.setStatus("ORDER_DUBIOUS");
			sLSHttpInterfaceInfo.setSupOrderNo(orderId);
		}

		sLSHttpInterfaceInfo.setGameAccount(info.getGameAccount());
		sLSHttpInterfaceInfo.setUnitPrice(info.getUnitPrice());
		sLSHttpInterfaceInfo.setBuyNum(info.getBuyNum());

		String totalPrice = info.getTotalPrice();
		sLSHttpInterfaceInfo.setTotalPrice(totalPrice);
		Gson gson = CommonUtil.gson();
		String resultBody = gson.toJson(sLSHttpInterfaceInfo);

		return resultBody;
	}

	private static SevenNineNineSixRespInfo trade(SLSHttpInterfaceInfo info,
			String originalGoodsId, String orderId, String orderTime,
			Head head, GoodsOrderDAO goodsOrderDAO,
			GoodsSupplyManageDAO goodsSupplyManageDAO,
			SevenNineNineSixDAO snnsDAO) {
		SevenNineNineSixRespInfo resInfo = null;
		String cid = PropertiesUtil.getValue("snns.interface.cid", filename);
		GoodsOrderInfo orderInfo = new GoodsOrderInfo();
		orderInfo.setRegisterAccount(cid);
		updateGoodsOrder(orderId, head, orderInfo, goodsOrderDAO);

		String url = assembleParameterOfTrade(info, originalGoodsId, orderId,
				orderTime, snnsDAO);
		// 发送http请求
		resInfo = sendHttpRequestOfDirectTrade(url, head);
		// 上游订单结果
		String orderResult = "";
		String msg = "";
		String status = "2";
		String sid = "";
		if (resInfo != null) {
			// 订单结果
			orderResult = resInfo.getResult();
			msg = resInfo.getMsg();
			if ("true".equals(orderResult)) { // 下单成功（订单状态处理中）
				sid = resInfo.getSid();
			} else if ("false".equals(orderResult)) {
				status = "0"; // 失败
			} else {
				status = "3"; // 存疑
			}
		} else {
			status = "3"; // 存疑
		}

		GoodsOrderInfo goodsOrderInfo = new GoodsOrderInfo();
		goodsOrderInfo.setStatus(status);
		goodsOrderInfo.setStatusRemark(msg);
		goodsOrderInfo.setSupOrderId(sid);
		try {
			// 根据交易返回的结果更新订单表
			updateGoodsOrder(orderId, head, goodsOrderInfo, goodsOrderDAO);
		} catch (Exception e) {
			log.error("请求ID：" + head.getRequestId() + "根据7996返回的结果更新订单异常！", e);
		}
		return resInfo;
	}

	/**
	 * 更新订单
	 * 
	 * @param orderId
	 * @param head
	 * @param info
	 * @param goodsOrderDAO
	 */
	private static void updateGoodsOrder(String orderId, Head head,
			GoodsOrderInfo info, GoodsOrderDAO goodsOrderDAO) {
		info.setOrderId(orderId);
		info.setSynOrAsy("0"); // 同步通知标识
		// 数据更新
		try {
			goodsOrderDAO.update(info);
		} catch (Exception e) {
			log.error(
					"updateGoodsOrder处理[" + head.getRequestId() + "]的请求出现异常！",
					e);
		}
	}

	/**
	 * 向上游发送交易请求
	 * 
	 * @param address
	 * @param paraStr
	 * @param head
	 * @return
	 */
	private static SevenNineNineSixRespInfo sendHttpRequestOfDirectTrade(
			String url, Head head) {
		SevenNineNineSixRespInfo resInfo = null;
		HttpClient httpClient = new HttpClient();
		try {
			// 供应商返回消息编码方式
			String supplyEncode = "GB2312";
			log.info("请求ID：" + head.getRequestId() + "，发送到7996的直充请求url参数为："
					+ url);
			String xmlStr = httpClient.doGet(url, supplyEncode);
			log.info("请求ID：" + head.getRequestId() + "，7996直充返回的结果参数为："
					+ xmlStr);
			// 对返回的xml格式字符串数据进行解析
			if (StringUtils.isNotEmpty(xmlStr)) {
				resInfo = ParseResponseInfo.parse(xmlStr);
			}
		} catch (Exception e) {
			log.error("请求ID：" + head.getRequestId() + "7996直充交易请求异常！", e);
		}
		return resInfo;
	}

	/**
	 * 拼装请求地址
	 * 
	 * @param info
	 * @param originalGoodsId
	 * @param orderId
	 * @param orderTime
	 * @param jpayGoodsDAO
	 * @return
	 */
	private static String assembleParameterOfTrade(SLSHttpInterfaceInfo info,
			String originalGoodsId, String orderId, String orderTime,
			SevenNineNineSixDAO snnsDAO) {
		String url = "";
		String address = PropertiesUtil.getValue(
				"snns.interface.recharge.address", filename);
		String cid = PropertiesUtil.getValue("snns.interface.cid", filename);
		String pn = info.getGameAccount();
		String pr = "";
		SevenNineNineSixProduct sProduct = snnsDAO
				.queryByProductId(originalGoodsId);
		if (sProduct != null) {
			pr = sProduct.getProductParvalue();
		}
		String nb = info.getBuyNum();
		int fm = 0;
		if (pr.indexOf(".") > 0) {
			pr = pr.substring(0, pr.indexOf("."));
			int num = 0;
			int parvalue = 0;
			try {
				num = Integer.parseInt(nb);
				parvalue = Integer.parseInt(pr);
			} catch (Exception e) {
				log.error("格式转换异常", e);
			}
			fm = parvalue * num;
		}
		String md5key = PropertiesUtil.getValue("snns.md5.key", filename);
		String ru = PropertiesUtil.getValue("snns.return.address", filename);
		String at = info.getAccountTypeName();
		String ct = info.getChargeTypeName();
		String fr = info.getGameArea();
		String fs = info.getGameServer();
		String data = orderId + cid + originalGoodsId + pn + pr + nb + fm + ru
				+ md5key;
		String sign = UtilMD5Encryption.createMD5EncryptionOfGBK(data);
		StringBuilder sb = new StringBuilder();
		sb.append(address);
		sb.append("?");
		sb.append("oid=");
		sb.append(orderId);
		sb.append("&");
		sb.append("cid=");
		sb.append(cid);
		sb.append("&");
		sb.append("pid=");
		sb.append(originalGoodsId);
		sb.append("&");
		sb.append("pn=");
		sb.append(pn);
		sb.append("&");
		sb.append("pr=");
		sb.append(pr);
		sb.append("&");
		sb.append("nb=");
		sb.append(nb);
		sb.append("&");
		sb.append("fm=");
		sb.append(fm);
		sb.append("&");
		sb.append("ru=");
		sb.append(ru);
		if (StringUtils.isNotEmpty(at)) {
			sb.append("&");
			sb.append("at=");
			sb.append(at);
		}
		if (StringUtils.isNotEmpty(ct)) {
			sb.append("&");
			sb.append("ct=");
			sb.append(ct);
		}
		if (StringUtils.isNotEmpty(fr)) {
			sb.append("&");
			sb.append("fr=");
			sb.append(fr);
		}
		if (StringUtils.isNotEmpty(fs)) {
			sb.append("&");
			sb.append("fs=");
			sb.append(fs);
		}
		sb.append("&");
		sb.append("sign=");
		sb.append(sign);
		url = sb.toString();
		return url;

	}

}
